package com.tmz.cloudmall.cloudmallgateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class RequestResponseLoggingFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取完整的请求URI（包含路径和查询参数等）
        String fullRequestUri = request.getURI().toString();
        // 记录完整的请求路径
        log.info("完整请求路径: {}", fullRequestUri);
        // 也可以继续记录原来的路径等信息，这里主要是添加完整请求路径的打印
        log.info("请求路径: {}, 目标服务: {}", request.getPath(),
                request.getHeaders().getFirst("X-Forwarded-Service"));

        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    ServerHttpResponse response = exchange.getResponse();
                    log.info("响应状态码: {}, 响应体（部分，实际可根据需求获取完整响应体）: {}",
                            response.getStatusCode(), "响应体内容（此处可通过自定义方式获取完整响应体）");
                })
        );
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE; // 设置过滤器顺序，确保在最后执行
    }
}
